// 涨停股Vue组件
const ZhangtingComponent = {
    template: `
        <div class="zhangting-page">
            <div class="page-header">
                <h2>涨停股</h2>
                <div class="header-actions">
                    <input 
                        type="date" 
                        v-model="selectedQueryDate"
                        style="margin-right: 10px; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;"
                        @change="handleDateChange">
                    <el-input
                        v-model="filterKeyword"
                        placeholder="搜索股票名称/代码/原因"
                        style="width: 200px; margin-right: 10px;"
                        clearable
                        @input="handleFilterChange">
                        <template #prefix>
                            <i class="el-icon-search"></i>
                        </template>
                    </el-input>
                    <el-button type="primary" @click="queryByDate" :loading="loading">
                        <i class="el-icon-search"></i>
                        查询
                    </el-button>
                    <el-button @click="loadRecentData" :loading="loading">
                        <i class="el-icon-refresh"></i>
                        最近数据
                    </el-button>
                    <el-button @click="resetSelection">
                        <i class="el-icon-close"></i>
                        清除选择
                    </el-button>
                </div>
            </div>

            <!-- 查询状态提示 -->
            <div class="query-status">
                <el-alert
                    v-if="currentQueryType === 'recent'"
                    title="正在显示最近日期的涨停股数据"
                    type="success"
                    :closable="false"
                    show-icon>
                </el-alert>
                <el-alert
                    v-else-if="currentQueryType === 'date' && selectedQueryDate"
                    :title="'正在显示 ' + selectedQueryDate + ' 的涨停股数据'"
                    type="info"
                    :closable="false"
                    show-icon>
                </el-alert>
            </div>

            <!-- 统计信息 -->
            <div class="statistics-panel" v-if="zhangtingData.length > 0">
                <h3>统计信息</h3>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">涨停股数量</div>
                            <div class="stat-value">{{ zhangtingData.length }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">筛选结果</div>
                            <div class="stat-value">{{ filteredData.length }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">平均涨幅</div>
                            <div class="stat-value">{{ getAverageZtPercent() }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">最后更新时间</div>
                            <div class="stat-value">{{ lastUpdateTime }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 涨停股表格 -->
            <div class="zhangting-container">
                <table class="zhangting-table" v-if="filteredData.length > 0">
                    <thead>
                        <tr>
                            <th>代码</th>
                            <th>名称</th>
                            <th>收盘价</th>
                            <th>涨跌幅</th>
                            <th>首次涨停</th>
                            <th>最后涨停</th>
                            <th>连续天数</th>
                            <th>几天几板</th>
                            <th>涨停类型</th>
                            <th>涨停原因</th>
                            <th>封单量</th>
                            <th>封单额</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in filteredData" 
                            :key="item.code"
                            :class="getRowClass(item)"
                            @click="handleRowClick(item)">
                            <td>{{ item.code || item.stockCode || '-' }}</td>
                            <td class="stock-name">{{ item.name || '-' }}</td>
                            <td>{{ item.close || '-' }}</td>
                            <td class="percent">
                                <span :style="{ color: getChangeColor(item.zhangdiefu) }">
                                    {{ formatPercent(item.zhangdiefu) }}
                                </span>
                            </td>
                            <td class="time">{{ formatTime(item.firstTime) }}</td>
                            <td class="time">{{ formatTime(item.endTime) }}</td>
                            <td>{{ item.lianxuZhangtingDays || '-' }}</td>
                            <td>{{ item.jitianJiban || '-' }}</td>
                            <td>{{ item.zhangtingType || '-' }}</td>
                            <td class="reason-cell">{{ item.zhangtingReasonType || '-' }}</td>
                            <td>{{ formatVolume(item.zhangtingFengdanliang) }}</td>
                            <td>{{ formatAmount(item.zhangtingFengdane) }}</td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- 无数据提示 -->
                <el-empty v-else description="暂无涨停股数据" :image-size="200">
                    <el-button type="primary" @click="refreshData">刷新数据</el-button>
                </el-empty>
            </div>

            <!-- 股票详情面板 -->
            <div class="stock-detail-panel" v-if="selectedStock">
                <div class="panel-header">
                    <h3>{{ selectedStock.name }} ({{ selectedStock.code }})</h3>
                    <button class="close-btn" @click="selectedStock = null">×</button>
                </div>
                <div class="detail-content">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-card class="stat-card">
                                <div class="stat-title">收盘价</div>
                                <div class="stat-value">{{ selectedStock.close || '-' }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="6">
                            <el-card class="stat-card">
                                <div class="stat-title">涨跌幅</div>
                                <div class="stat-value" :style="{ color: getChangeColor(selectedStock.zhangdiefu) }">
                                    {{ formatPercent(selectedStock.zhangdiefu) }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">连续天数</div>
                                <div class="stat-value">{{ selectedStock.lianxuZhangtingDays || '-' }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">几天几板</div>
                                <div class="stat-value">{{ selectedStock.jitianJiban || '-' }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">涨停类型</div>
                                <div class="stat-value">{{ selectedStock.zhangtingType || '-' }}</div>
                            </el-card>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" style="margin-top: 20px;">
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">涨停原因</div>
                                <div class="stat-value">{{ selectedStock.zhangtingReasonType || '-' }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">封单额</div>
                                <div class="stat-value">{{ formatAmount(selectedStock.zhangtingFengdane) }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">首次涨停</div>
                                <div class="stat-value">{{ formatTime(selectedStock.firstTime) }}</div>
                            </el-card>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" style="margin-top: 20px;">
                        <el-col :span="12">
                            <el-card class="stat-card">
                                <div class="stat-title">最后涨停</div>
                                <div class="stat-value">{{ formatTime(selectedStock.endTime) }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="12">
                            <el-card class="stat-card">
                                <div class="stat-title">封单量</div>
                                <div class="stat-value">{{ formatVolume(selectedStock.zhangtingFengdanliang) }}</div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>
            </div>

          </div>
    `,
    
    data() {
        // 获取当前日期并格式化为YYYY-MM-DD
        const today = new Date();
        const currentDate = today.getFullYear() + '-' + 
                          String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                          String(today.getDate()).padStart(2, '0');
        
        return {
            loading: false,
            lastUpdateTime: new Date().toLocaleString(),
            filterKeyword: '',
            selectedQueryDate: currentDate,
            currentQueryType: 'date', // 'recent', 'date' - 改为date以默认加载当前日期数据
            zhangtingData: [],
            selectedStock: null
        }
    },
    
    computed: {
        filteredData() {
            return this.filterData(this.zhangtingData);
        }
    },
    
    methods: {
        async refreshData() {
            this.loading = true;
            try {
                await this.loadZhangtingData();
                this.lastUpdateTime = new Date().toLocaleString();
            } finally {
                this.loading = false;
            }
        },
        
        async loadZhangtingData() {
            try {
                let url;
                if (this.currentQueryType === 'date' && this.selectedQueryDate) {
                    // 格式化日期为yyyyMMdd
                    const formattedDate = this.selectedQueryDate.replace(/-/g, '');
                    url = `/api/zhangting/${formattedDate}`;
                    console.log('正在请求指定日期涨停股数据URL:', url);
                } else {
                    url = `/api/zhangting/get`;
                    console.log('正在请求涨停股数据URL:', url);
                }
                
                const response = await axios.get(url);
                console.log('涨停股数据API响应:', response.data);
                
                if (response.data && response.data.code === 200) {
                    const zhangtingData = response.data.data || [];
                    this.processZhangtingData(zhangtingData);
                    console.log('成功加载涨停股数据');
                } else if (Array.isArray(response.data)) {
                    // 直接返回数组的情况
                    this.processZhangtingData(response.data);
                    console.log('成功加载涨停股数据');
                } else {
                    console.error('涨停股数据格式异常:', response.data);
                }
            } catch (error) {
                console.error('加载涨停股数据失败:', error);
                if (window.ElMessage) {
                    window.ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message));
                }
            }
        },
        
        async queryByDate() {
            if (!this.selectedQueryDate) {
                if (window.ElMessage) {
                    window.ElMessage.warning('请选择查询日期');
                }
                return;
            }
            
            this.currentQueryType = 'date';
            this.resetSelection();
            await this.refreshData();
        },
        
        async loadRecentData() {
            this.currentQueryType = 'recent';
            this.selectedQueryDate = null;
            this.resetSelection();
            await this.refreshData();
        },
        
        handleDateChange(value) {
            // 日期改变时自动查询
            if (value) {
                this.queryByDate();
            }
        },

        processZhangtingData(data) {
            console.log('开始处理涨停股数据:', data);
            
            if (!Array.isArray(data)) {
                console.error('涨停股数据格式错误: 不是数组格式');
                this.zhangtingData = [];
                return;
            }

            // 数据处理和字段检查
            const processedData = data.map(item => {
                console.log('处理股票数据:', {
                    code: item.code || item.stockCode,
                    name: item.name,
                    firstTime: item.firstTime,
                    endTime: item.endTime,
                    lianxuZhangtingDays: item.lianxuZhangtingDays,
                    jitianJiban: item.jitianJiban,
                    zhangtingType: item.zhangtingType,
                    zhangtingReasonType: item.zhangtingReasonType,
                    zhangtingFengdanliang: item.zhangtingFengdanliang,
                    zhangtingFengdane: item.zhangtingFengdane
                });
                return item;
            });

            // 按日期排序
            this.zhangtingData = processedData.sort((a, b) => new Date(b.dateTime) - new Date(a.dateTime));
            console.log('处理后的涨停股数据数量:', this.zhangtingData.length);
            
            // 显示第一条数据的详细信息用于调试
            if (this.zhangtingData.length > 0) {
                console.log('第一条涨停股数据详情:', this.zhangtingData[0]);
            }
        },
        
        resetSelection() {
            this.selectedStock = null;
            this.filterKeyword = '';
        },
        
        handleFilterChange() {
            // 筛选逻辑已移到computed属性中
        },
        
        getRowClass(item) {
            return {
                'selected-row': this.selectedStock && this.selectedStock.code === item.code
            };
        },
        
        handleRowClick(item) {
            this.selectedStock = item;
        },
        
        formatDate(dateStr) {
            if (!dateStr) return '';
            if (dateStr.length === 8) {
                return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
            }
            return dateStr;
        },
        
        formatTime(timeStr) {
            if (!timeStr) return '-';
            if (timeStr.length === 6) {
                return `${timeStr.substring(0, 2)}:${timeStr.substring(2, 4)}:${timeStr.substring(4, 6)}`;
            }
            return timeStr;
        },
        
        formatPercent(value) {
            if (!value && value !== 0) return '-';
            const num = parseFloat(value);
            return `${num.toFixed(2)}%`;
        },
        
        getChangeColor(value) {
            if (!value && value !== 0) return '#606266';
            const num = parseFloat(value);
            if (num > 0) return '#f56c6c'; // 红色涨
            if (num < 0) return '#67c23a'; // 绿色跌
            return '#606266'; // 灰色平
        },
        
        formatAmount(amount) {
            if (!amount || amount === '0' || amount === '0.00') return '-';
            const num = parseFloat(amount);
            if (num >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (num >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toFixed(2);
        },
        
        formatVolume(volume) {
            if (!volume || volume === '0' || volume === '0.00') return '-';
            const num = parseFloat(volume);
            if (num >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (num >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toFixed(0);
        },
        
        filterData(data) {
            if (!this.filterKeyword) return data;
            const keyword = this.filterKeyword.toLowerCase();
            return data.filter(item => 
                (item.name && item.name.toLowerCase().includes(keyword)) ||
                (item.code && item.code.toLowerCase().includes(keyword)) ||
                (item.zhangtingReasonType && item.zhangtingReasonType.toLowerCase().includes(keyword)) ||
                (item.zhangtingType && item.zhangtingType.toLowerCase().includes(keyword)) ||
                (item.jitianJiban && item.jitianJiban.toLowerCase().includes(keyword))
            );
        },
        
        getAverageZtPercent() {
            if (this.zhangtingData.length === 0) return '0%';
            const sum = this.zhangtingData.reduce((acc, item) => acc + (item.ztPercent || 0), 0);
            return `${(sum / this.zhangtingData.length).toFixed(2)}%`;
        }
    },
    
    mounted() {
        // 默认加载当前日期的数据
        this.refreshData();
    }
};